package com.fubowen.reader.ui

import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import android.widget.TextView
import androidx.activity.OnBackPressedCallback
import androidx.constraintlayout.motion.widget.MotionLayout
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.fubowen.reader.R
import com.fubowen.reader.adapter.BookChapterAdapter
import com.fubowen.reader.adapter.SliderHelper
import com.fubowen.reader.components.SlideControlLayoutManager
import com.fubowen.reader.databinding.ReaderBinding
import com.fubowen.reader.db.database
import com.fubowen.reader.extension.setScreenBrightness
import com.fubowen.reader.extension.setVisible
import com.fubowen.reader.extension.statusBarHeight
import com.fubowen.reader.vm.ReaderViewModel
import com.fubowen.reader.vm.ThemeViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import java.util.Locale
import java.util.Timer
import java.util.TimerTask

class ReaderFragment : Fragment(), CatalogFragment.CloseCatalogView {

    private lateinit var onBackCallback: OnBackPressedCallback
    private lateinit var binding: ReaderBinding
    private lateinit var motionLayout: MotionLayout
    private lateinit var layoutManager: SlideControlLayoutManager
    private lateinit var recycler: RecyclerView
    private lateinit var timer: Timer
    private lateinit var adapter: BookChapterAdapter
    private lateinit var textToSpeech: TextToSpeech
    private var isAutoReader = false
    private var dispatcher = Dispatchers.IO
    private var isUserScroll = true
    private val catalog = lazy { CatalogFragment.newInstance(0.6f) }
    private var chapterPosition = 0
    private val args: ReaderFragmentArgs by navArgs()
    private val themeViewModel by activityViewModels<ThemeViewModel>()
    private val readerViewModel by activityViewModels<ReaderViewModel>()
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        goBack()
        binding = ReaderBinding.inflate(inflater, container, false)
        motionLayout = binding.reader
        setStatusBarHeight()
        initRecyclerView()
        initBottomMenu()
        initTopMenu()
        initSettingMenu()
        setLight()
        setPageTurn()
        setLineSpacing()
        setFontSize()
        setBackground()
        setTextToSpeech()
        setAutoReader()
        initOpenBook()
        SliderHelper(binding.readerMenu).onCloseAction = {
            motionLayout.transitionToState(R.id.reader_footer_step_2)
        }
//        onChangedTheme = {
//            checkOrSet(BACKGROUND_COLOR) {
//                viewModel.setBackgroundColor(Color.parseColor(it))
//            }
//            checkOrSet(TEXT_COLOR) {
//                viewModel.setColor(Color.parseColor(it))
//            }
//            refresh()
//        }
        return binding.root
    }

    //region initTopMenu
    private fun initTopMenu() {
        binding.readerBack.setOnClickListener { goBackBookshelf() }
        binding.readerBookshelf.setOnClickListener { }
        binding.readerDownload.setOnClickListener { }
        binding.readerBookmark.setOnClickListener { }
    }
    //endregion

    //region initBottomMenu
    private fun initBottomMenu() {
        binding.readerPrev.setOnClickListener {
            recycler.scrollToPosition(--chapterPosition)
        }
        binding.readerCatalog.setOnClickListener {
            catalog.value.show(
                parentFragmentManager,
                "CATALOG"
            )
        }
        binding.readerSetting.setOnClickListener {
            val next = when (motionLayout.currentState) {
                R.id.reader_footer_step_2 -> R.id.reader_footer_step_3
                R.id.reader_footer_step_3 -> R.id.reader_footer_step_2
                else -> R.id.reader_footer_step_1
            }
            motionLayout.transitionToState(next)
        }
        binding.readerNext.setOnClickListener {
            recycler.scrollToPosition(++chapterPosition)
        }
    }
    //endregion

    //region initRecyclerView
    private fun initRecyclerView() {
        recycler = binding.readerContent
        layoutManager = SlideControlLayoutManager(requireContext())
        adapter = BookChapterAdapter(layoutManager, requireContext(), themeViewModel)
        recycler.layoutManager = layoutManager
        recycler.adapter = adapter
        recycler.addOnScrollListener(onScrolledOfRecyclerView())
        recycler.addOnItemTouchListener(onItemTouchOfRecyclerView())
    }

    private fun onScrolledOfRecyclerView() = object : RecyclerView.OnScrollListener() {
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            chapterPosition = layoutManager.findFirstVisibleItemPosition()
            val item = adapter.peek(chapterPosition)
            if (item != null) {
                binding.readerTitle.text = String.format("第%d章 %s", item.order, item.name)
                if (isUserScroll) {
                    if (item.content.isNotBlank()) {
                        val progress = getReadingProgress()
                        CoroutineScope(dispatcher).launch {
//                            viewModel.sendReadingProgress(Triple(item.bookId, item.id, progress))
                        }
                    }
                }
            }
        }
    }

    private fun onItemTouchOfRecyclerView() = object : RecyclerView.OnItemTouchListener {

        override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
            if (e.action == MotionEvent.ACTION_DOWN && motionLayout.currentState != R.id.reader_footer_step_1) {
                motionLayout.transitionToState(R.id.reader_footer_step_1)
            }
            return false
        }

        override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {}

        override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}
    }
    //endregion

    //region 返回监听
    private fun goBack() {
        onBackCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                goBackImpl()
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(
            viewLifecycleOwner,
            onBackCallback
        )
    }

    private fun goBackImpl() {
        if (!catalog.value.isResumed) {
            if (motionLayout.currentState != R.id.reader_footer_step_1) {
                motionLayout.transitionToState(R.id.reader_footer_step_1)
            } else {
                goBackBookshelf()
            }
        } else {
            catalog.value.dismiss()
        }
    }

    private fun goBackBookshelf() {
        findNavController().navigateUp()
        onBackCallback.isEnabled = false
    }

    //endregion

    //region 打开菜单，切换目录，切换更多设置

    private fun initSettingMenu() {
        adapter.setOnClickListener(object : BookChapterAdapter.OnClickListener {
            override fun onItemClick(view: View?) {
                val next = when (motionLayout.currentState) {
                    R.id.reader_footer_step_1 -> R.id.reader_footer_step_2
                    R.id.reader_footer_step_2 -> R.id.reader_footer_step_1
                    R.id.reader_footer_step_3 -> R.id.reader_footer_step_1
                    else -> R.id.reader_footer_step_1
                }
                motionLayout.transitionToState(next)
            }
        })
    }

    //endregion

    //region 状态栏高度，亮度设定

    private fun setStatusBarHeight() {
        binding.readerStatusBar.apply {
            updateLayoutParams<ViewGroup.MarginLayoutParams> {
                height = requireContext().statusBarHeight
            }
        }
    }

    private fun OnSeekBarChangeListener() = object : SeekBar.OnSeekBarChangeListener {
        override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
            requireActivity().window.setScreenBrightness(progress)
        }

        override fun onStartTrackingTouch(seekBar: SeekBar?) {}

        override fun onStopTrackingTouch(seekBar: SeekBar?) {}
    }

    private fun setLight() {
        binding.readerLight.setOnSeekBarChangeListener(OnSeekBarChangeListener())
        binding.readerLightEye.setOnClickListener { settProtectEyeMode() }
    }

    //endregion

    //region 设置护眼模式，字体大小，行距，主题，自动阅读

    private fun settProtectEyeMode() {
        val drawable = motionLayout.background
        if (drawable is ColorDrawable) {
            val oldColor = drawable.color
//            val newColor = changeColor(oldColor, 65f, 0.30f, 0.78f)
//            motionLayout.setThemeColor(newColor)
//            viewModel.setBackgroundColor { newColor }
            refresh()
        }
    }

    private fun setFontSize() {

        binding.readerFsAdd.setOnClickListener {
//            viewModel.setTextSize {
//                it.plus(1)
//                binding.readerFs.text = it.toString()
//                it
//            }
            refresh()
        }
        binding.readerFsSub.setOnClickListener {
//            viewModel.setTextSize {
//                it.minus(1)
//                binding.readerFs.text = it.toString()
//                it
//            }
            refresh()
        }
    }

    private fun setLineSpacing() {

        fun set(lineSpacing: Float) {
//            viewModel.setLineSpacingMultiplier { lineSpacing }
            refresh()
        }
        binding.readerLh1.setOnClickListener { set(lineSpacing = 1.0F) }
        binding.readerLh2.setOnClickListener { set(lineSpacing = 1.5F) }
        binding.readerLh3.setOnClickListener { set(lineSpacing = 2.0F) }
        binding.readerLh4.setOnClickListener { set(lineSpacing = 2.5F) }
    }

    private fun setBackground() {

//        fun set(id: Int) {
//            val color = requireContext().getColor(id)
//            motionLayout.setThemeColor(color)
////            viewModel.setBackgroundColor { color }
//            refresh()
//        }
//
//        binding.reader.apply {
//            binding.readerBg0.setOnClickListener { set(R.color.reader_0) }
//            binding.readerBg1.setOnClickListener { set(R.color.reader_1) }
//            binding.readerBg2.setOnClickListener { set(R.color.reader_2) }
//            binding.readerBg3.setOnClickListener { set(R.color.reader_3) }
//        }
    }

    private fun setTextToSpeech() {
        binding.readerSpeech.setOnClickListener {
            textToSpeech.speak("123123123", TextToSpeech.QUEUE_FLUSH, null, null)
        }
        textToSpeech = TextToSpeech(requireContext()) {
            if (it == TextToSpeech.SUCCESS) {
                val result = textToSpeech.setLanguage(Locale.getDefault())
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    binding.readerSpeech.setVisible(false)
                }
            } else {
                binding.readerSpeech.setVisible(false)
            }
        }
    }

    private fun setAutoReader() {
        binding.readerAuto.setOnClickListener {
            if (isAutoReader) {
                stopAutoReader()
                isAutoReader = false
                binding.readerAuto.text = "开启自动阅读"
                binding.readerAuto.setTextColor(Color.WHITE)
            } else {
                startAutoReader()
                isAutoReader = true
                binding.readerAuto.text = "关闭自动阅读"
                binding.readerAuto.setTextColor(Color.GREEN)
            }
        }
    }

    private fun startAutoReader() {
        val speed: Long = 10
        val dy = 100
        val task = object : TimerTask() {
            override fun run() {
                binding.readerContent.apply {
                    post {
                        smoothScrollBy(0, dy)
                    }
                }
            }
        }
        timer = Timer()
        timer.schedule(task, speed, speed)
    }

    private fun stopAutoReader() {
        timer.cancel()
        timer.purge()
    }

    private fun setPageTurn() {
        val pagerSnapHelper = PagerSnapHelper()
        binding.readerFySx.setOnClickListener {
            val llm = binding.readerContent.layoutManager as LinearLayoutManager
            llm.orientation = LinearLayoutManager.VERTICAL
            pagerSnapHelper.attachToRecyclerView(null)
        }
        binding.readerFyZy.setOnClickListener {
            val llm = binding.readerContent.layoutManager as LinearLayoutManager
            llm.orientation = LinearLayoutManager.HORIZONTAL
            pagerSnapHelper.attachToRecyclerView(binding.readerContent)
        }
    }

    //endregion

    //region 获得阅读进度

    private fun getReadingProgress(): Int {
        val position = layoutManager.findFirstVisibleItemPosition()
        val holder = recycler.findViewHolderForAdapterPosition(position)
        var charIndex = 0
        if (holder != null) {
            val chapterContent = holder.itemView.findViewById<TextView>(R.id.chapter_content)
            val rect = Rect()
            chapterContent.getLocalVisibleRect(rect)
            charIndex =
                chapterContent.getOffsetForPosition(rect.left.toFloat(), rect.top.toFloat())
        }
        return charIndex
    }

    //endregion

    //region 子级调用的方法 close
    override fun close() {
        if (motionLayout.currentState != R.id.reader_footer_step_1) {
            motionLayout.transitionToState(R.id.reader_footer_step_1)
        }
    }

    override fun jumpChapter(position: Int) {
        recycler.scrollToPosition(position)
    }
    //endregion

    //region 加载正在阅读的书籍
    private fun initOpenBook() {
        val statusBarHeight = requireContext().statusBarHeight
        val sh = resources.displayMetrics.heightPixels - statusBarHeight - 30 * 3 + 0f
        val sw = resources.displayMetrics.widthPixels - 32 * 3 + 0f
        readerViewModel.setHeight(sh)
        readerViewModel.setWidth(sw)
        lifecycleScope.launch {
            val chapter = requireContext().database.bookDao().getReadingChapter(args.id)
            if (chapter != null) {
                setReadingProgress(chapter.order, chapter.position)
            }
            readerViewModel.bookChapterFlow(args.id).collectLatest { pagingData ->
                adapter.submitData(pagingData)
            }
        }
    }

    private fun refresh() = adapter.refresh()

    private fun setReadingProgress(order: Int, position: Int) {
        recycler.scrollToPosition(order - 1)
        recycler.post {
            val holder = recycler.findViewHolderForAdapterPosition(order - 1)
            if (holder is BookChapterAdapter.ViewHolder) {
                holder.content.apply {
                    val lineNumber = layout.getLineForOffset(position)
                    val top = layout.getLineTop(lineNumber)
                    val tvPoint = IntArray(2)
                    getLocationInWindow(tvPoint)
                    val rvPoint = IntArray(2)
                    recycler.getLocationInWindow(rvPoint)
                    val dy = rvPoint[1] + tvPoint[1] + top
                    recycler.scrollBy(0, dy)
                }
            }
        }
    }

    //endregion
}



